#include "BlockQueue.hpp"
#include <iostream>
#include <unistd.h>
#include <time.h>
#include "Task.h"
using namespace std;



// int main()
// {
//     queue<int> q;
//     pthread_mutex_t mutex;
//     pthread_cond_t c_cond;
//     pthread_cond_t p_cond;
   
//     vector<BlockQueue*> c(5), p(3);
//     for(int i = 0; i < 5; ++i)
//     {
//         description* info = new description();
//         info->_name = "Consumer-" + to_string(i + 1);
//         BlockQueue* bq = new BlockQueue(info, &p_cond, &c_cond, &mutex, &q);
//         c[i] = bq;

//         pthread_create(&(info->_pid), nullptr, Consume, bq);
//     }
//     for(int i = 0; i < 3; ++i)
//     {
//         description* info = new description();
//         info->_name = "Producer-" + to_string(i + 1);
        
//         BlockQueue* bq = new BlockQueue(info, &p_cond, &c_cond, &mutex, &q);
//         p[i] = bq;
//         pthread_create(&(info->_pid), nullptr, Consume, bq);
//     }


//     for(int i = 0; i < 5; ++i)
//     {
//         pthread_join((c[i]->_info)->_pid, nullptr);
//     }
//     return 0;
// }

void* Consume(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    while(1)
    {
        Task data = bq->pop();
        //cout <<"C:"<< pthread_self() % 100000<< "- get[" << data << "]"<< endl;
        //usleep(1000000);  
        data();
        cout << pthread_self() % 100000 << " 计算结果：" << data.getans() << endl;
        sleep(1);
    }
  
    return nullptr;
}

void* Produce(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    while(1)
    {
        int data1 = rand() % 100 + 1;
        usleep(15);
        int data2 = rand() % 100 + 1;
        usleep(5);
        char oper = op[rand() % op.size()];

        bq->push(Task(data1, data2, oper));
        //cout <<"P:"<< pthread_self() % 100000<< "- push[" << data << "]"<< endl;
        //usleep(1000000);
        sleep(1);
    }
    return nullptr;
}

int main()
{
    BlockQueue<Task>* bq = new BlockQueue<Task>();
    srand(time(nullptr));
    vector<description*> c(3), p(5);


    for(int i = 0; i < 5; ++i)
    {
        description* info = new description();
        info->_name = "Producer-" + to_string(i + 1);
        p[i] = info;
        pthread_create(&(info->_pid), nullptr, Produce, bq);
        //cout << "创建：" << info->_name << endl;
    }
    for(int i = 0; i < 3; ++i)
    {
        description* info = new description();
        info->_name = "Consumer-" + to_string(i + 1);
        c[i] = info;
        pthread_create(&(info->_pid), nullptr, Consume, bq);
        //cout << "创建：" << info->_name << endl;
    }

    for(int i = 0; i < 3; ++i)
    {
        pthread_join(c[i]->_pid, nullptr);
        delete c[i];
    }
    for(int i = 0; i < 5; ++i)
    {
        pthread_join(p[i]->_pid, nullptr);
        delete p[i];
    }
    delete bq;
    return 0;
}